package com.leetcodehot.problems;

public class problems25_Reverse {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        while (head != null) {
            ListNode tail = prev;
            for (int i = 0; i < k; i++) {
                tail = tail.next;
                if (tail == null) {
                    return dummy.next;
                }
            }
            ListNode next = tail.next;
            ListNode[] reverse = myReverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            //重新接回链表
            prev.next = head;
            tail.next = next;
            prev = tail;
            head = next;
        }
        return dummy.next;
    }

    public ListNode[] myReverse(ListNode head, ListNode tail) {
        //将整段链表reverse 包括head
        ListNode dummy = new ListNode(0);
        ListNode lastOne = head;
        dummy.next = null;
        tail.next = null;
        while(head!=null){
            ListNode temp = head.next;
            head.next = dummy.next;
            dummy.next = head;
            head = temp;
        }
        return new ListNode[]{dummy.next,lastOne};
    }
}